const fs = require("fs-extra");
const path = require("path");
const execa = require("execa");
const chalk = require("chalk");
const { gzipSync } = require("zlib");
const { compress } = require("brotli");
const args = require("minimist")(process.argv.slice(2));
const { resolve, pkg } = require("./utils");
const name = pkg.name;
const prodOnly = args.prodOnly || args.p || false;
const devOnly = !prodOnly && (args.devOnly || args.d || true);
const env = devOnly ? "development" : "production";
const distPath = resolve("./dist");
run();
async function run() {
  cleanFolder();
  await execBundler();
  addFile();
  checkAllSizes();
}
function cleanFolder() {
  fs.removeSync(distPath);
}
async function execBundler() {
  await execa(
    "rollup",
    [
      "-c",
      "--environment",
      [`NODE_ENV:${env}`, `__DEV__:${devOnly}`, `__PROD__:${prodOnly}`]
    ],
    {
      stdio: "inherit"
    }
  );
}
function addFile() {
  addIndex();
  addPackage();
}
function addIndex() {
  const indexFile = `"use strict";
if (process.env.NODE_ENV === "production") {
  module.exports = require("./src/${name}.cjs.prod.js");
} else {
  module.exports = require("./src/${name}.cjs.js");
}
`;
  fs.outputFileSync(`${distPath}/index.js`, indexFile);
}
function addPackage() {
  pkg.typings = "src/index.d.ts";
  pkg.main = "index.js";
  pkg.module = "src/index.esm-bundler.js";
  pkg.files = ["index.js", "dist"];
  fs.writeJSONSync(`${distPath}/package.json`, pkg);
}
function checkAllSizes(target) {
  const files = fs.readdirSync(`${distPath}/src`).filter((f) => {
    return /^bestlyg-data-structures./.test(f);
  });
  for (const file of files) {
    checkSize(file);
  }
}
function checkSize(target) {
  checkFileSize(`${distPath}/src/${target}`);
}
function checkFileSize(filePath) {
  if (!fs.existsSync(filePath)) return;
  const file = fs.readFileSync(filePath);
  const minSize = (file.length / 1024).toFixed(2) + "kb";
  const gzipped = gzipSync(file);
  const gzippedSize = (gzipped.length / 1024).toFixed(2) + "kb";
  const compressed = compress(file);
  const compressedSize = (compressed.length / 1024).toFixed(2) + "kb";
  console.log(
    `${chalk.gray(
      chalk.bold(path.basename(filePath))
    )} min:${minSize} / gzip:${gzippedSize} / brotli:${compressedSize}`
  );
}
